package net.sourceforge.peers.sip.transport;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.AccessController;
import java.security.PrivilegedAction;

import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;

/**
 * 使用DatagramSocket发送消息 基于UDP
 * @author Mr.Yan
 */
public class UdpMessageSender extends MessageSender {

    private final DatagramSocket datagramSocket;
    
    public UdpMessageSender(InetAddress inetAddress, int port,
            DatagramSocket datagramSocket, Config config,
            Logger logger) {
        super(datagramSocket.getLocalPort(), inetAddress, port,
                config, RFC3261.TRANSPORT_UDP, logger);
        this.datagramSocket = datagramSocket;
    }

    @Override
    public synchronized void sendMessage(SipMessage sipMessage){
        logger.debug("UdpMessageSender.sendMessage");
        if (sipMessage == null) {
            return;
        }
        byte[] buf = sipMessage.toString().getBytes();
        sendBytes(buf);
        String direction = "SENT to " + inetAddress.getHostAddress() +
                "/" + port;
        String message = new String(buf);
        logger.traceNetwork(message, direction);
    }

    @Override
    public synchronized void sendBytes(byte[] bytes){
        logger.debug("UdpMessageSender.sendBytes");
        final DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
                inetAddress, port);
        logger.debug("UdpMessageSender.sendBytes " + bytes.length
                + " " + inetAddress + ":" + port);
        AccessController.doPrivileged(
                (PrivilegedAction<Void>) () -> {
                    try {
                        logger.debug(datagramSocket.getLocalAddress().toString());
                        datagramSocket.send(packet);
                    } catch (Throwable t) {
                        t.printStackTrace();
                        logger.error("throwable", new Exception(t));
                    }
                    return null;
                }
        );

        logger.debug("UdpMessageSender.sendBytes packet sent");
    }

}
